<template>
	<view class="updateSchedule">
		<view class="updateSchedule-label">
			<uni-segmented-control :current="current" :values="items" @clickItem="onClickItem" styleType="button"
				activeColor="#49bdfb"></uni-segmented-control>
		</view>
		<view class="updateSchedule-info">
			<!-- 日程表单 -->
			<uni-forms ref="form" :rules="rules" :modelValue="scheduleData">
				<uni-card v-if="scheduleData.label=='活动日程'">
					<view>
						<text style="font-size: 15px;">标题：{{scheduleData.title}}</text>
					</view>
					<view>
						<text style="font-size: 15px;">开始时间：{{scheduleData.beginTime}}</text>
					</view>
					<view>
						<text style="font-size: 15px;">结束时间：{{scheduleData.endTime}}</text>
					</view>
				</uni-card>
				<uni-card v-if="scheduleData.label=='个人日程'">
					<uni-forms-item label="名称" required name="title">
						<uni-easyinput v-model="scheduleData.title" placeholder="日程名称" :disabled="disable" />
					</uni-forms-item>
				</uni-card>
				<uni-card v-if="scheduleData.label=='个人日程'">
					<uni-forms-item label="开始" name="beginTime">
						<uni-datetime-picker type="datetime" return-type="string" v-model="defaultBeginTime"
							@change="changeBegin" :disabled="disable" />
					</uni-forms-item>
					<uni-forms-item label="结束" name="endTime">
						<uni-datetime-picker type="datetime" return-type="string" v-model="defaultEndTime"
							@change="changeEnd" :disabled="disable" />
					</uni-forms-item>
				</uni-card>
				<uni-card v-if="scheduleData.label=='活动日程'" style="margin: 0;">
					<view>
						<text style="font-size: 15px;">地点：{{scheduleData.location}}</text>
					</view>
					<view>
						<text style="font-size: 15px;">重复：{{scheduleData.frequency}}</text>
					</view>
					<view>
						<text style="font-size: 15px;">重复结束：{{scheduleData.repeatEndTime}}</text>
					</view>
				</uni-card>
				<view style="padding:10px 30px;">
					<uni-forms-item label="提醒" name="remind">
						<uni-data-select v-model="value" :localdata="remindRange" @change="remindChange" :clear="false">
						</uni-data-select>
					</uni-forms-item>
					<uni-forms-item label="重复" name="frequency" v-if="scheduleData.label=='个人日程'">
						
						<picker mode="multiSelector" :range="frequencyRange" :value="frequencyIndex"
							@columnchange="frequencyChange" :disabled="disable">
							<view style="background-color: white;margin: auto 15px;">
								{{scheduleData.frequency}}
							</view>
						</picker>
					</uni-forms-item>
					<uni-forms-item label="重复结束" name="repeatEndTime" v-if="scheduleData.label=='个人日程'">
						<picker mode="date" :value="date" :start="startDate" :end="endDate" @change="bindDateChange"
							:disabled="disable">
							<view style="margin: auto 15px;">{{date}}</view>
						</picker>
					</uni-forms-item>
				</view>
				
				<view style="padding:0 30px 10px" v-if="scheduleData.label=='个人日程'">
					<uni-forms-item label="地点" name="location">
						<uni-easyinput v-model="scheduleData.location" placeholder='请输入地点, 多个地点用","隔开'
							:disabled="disable" />
					</uni-forms-item>
				</view>
				<view style="padding:0 30px 0">
					<uni-forms-item label="备注" name="memo">
						<uni-easyinput v-model="scheduleData.memo" placeholder="日程备注" />
					</uni-forms-item>
				</view>
				<view class="updateSchedule-button">
					<button type="primary" @click="submit('form')" plain="true"
						class="updateSchedule-submit">修改</button>
				</view>
			</uni-forms>
		</view>
		<uni-popup ref="message" type="message">
			<uni-popup-message type="top" message="请检查日程结束时间是否小于开始时间" :duration="2000"></uni-popup-message>
		</uni-popup>
	</view>
</template>
<script>
	/* 时间戳转换成日期格式 */
	function formatDate(value) {
		if (value == undefined) {
			return;
		}
		// let date = new Date(value * 1000);
		let date = new Date(value);
		//时间戳为10位需*1000，时间戳为13位的话不需乘1000
		let y = date.getFullYear();
		let MM = date.getMonth() + 1;
		MM = MM < 10 ? ('0' + MM) : MM; //月补0
		let d = date.getDate();
		d = d < 10 ? ('0' + d) : d; //天补0
		let h = date.getHours();
		h = h < 10 ? ('0' + h) : h; //小时补0
		let m = date.getMinutes();
		m = m < 10 ? ('0' + m) : m; //分钟补0
		let s = date.getSeconds();
		s = s < 10 ? ('0' + s) : s; //秒补0
		return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s; //年月日时分秒
	}
	/* 日期增加 */
	function getDate(date, AddDayCount = 0) {
		if (!date) {
			date = new Date()
		}
		if (typeof date !== 'object') {
			date = date.replace(/-/g, '/')
		}
		const dd = new Date(date)

		dd.setDate(dd.getDate() + AddDayCount) // 获取AddDayCount天后的日期

		const y = dd.getFullYear()
		const m = dd.getMonth() + 1 < 10 ? '0' + (dd.getMonth() + 1) : dd.getMonth() + 1 // 获取当前月份的日期，不足10补0
		const d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate() // 获取当前几号，不足10补0
		return {
			fullDate: y + '-' + m + '-' + d,
			year: y,
			month: m,
			date: d,
			day: dd.getDay()
		}
	}
	export default {
		data() {
			const currentDate = this.getDateType({
				format: true
			})
			return {
				uid: 1,
				id: 0,
				apiUrl: "http://localhost:8080/",
				items: [],
				current: 0,
				defaultBeginTime: '',
				defaultEndTime: '',
				/* 日程数据 */
				scheduleData: {
					uid: 0,
					title: '',
					beginTime: '',
					endTime: '',
					remind: '',
					frequency: '',
					repeatEndTime: '',
					location: '',
					memo: '',
					label: '',
					activityId: 0,
				},
				/* 校验规则 */
				rules: {
					title: {
						rules: [{
							required: true,
							errorMessage: '日程名称不能为空'
						}]
					},
					scheduleEndTime: {
						rules: [{
							validateFunction: function(rule, value, data, callback) {
								if (value < this.defaultBeginTime) {
									callback('日程结束时间要大于开始时间')
								}
								return true
							}
						}]
					}

				},
				/* 重复选择 */
				value: 0,
				remindRange: [{
						value: 0,
						text: "不提醒"
					},
					{
						value: 1,
						text: "日程发生时"
					},
					{
						value: 2,
						text: "15分钟前"
					},
					{
						value: 3,
						text: "30分钟前"
					},
					{
						value: 4,
						text: "一个小时前"
					},
				],
				/* 重复 */
				frequencyRange: [
					['每'],
					['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
					['天', '周', '月', '年']
				],
				frequencyIndex: [0, 0, 0],
				/* 重复结束 */
				date: currentDate,
				/* 是否可以更改 */
				disable: false
			};
		},
		created() {},
		onReady() {
			// 需要在onReady中设置规则
			this.$refs.form.setRules(this.rules)
			console.log(this.scheduleData);
			console.log(this.value)
		},
		onLoad(option) {
			this.id = option.id
			/* 获取当前日程信息 */
			var url = ''
			url = this.apiUrl + 'schedule/' + this.id
			uni.request({
				url: this.apiUrl + 'schedule/' + this.id,
				method: 'GET',
				success: (res) => {
					this.id = res.data.id
					this.uid = res.data.uid
					this.scheduleData = res.data
					var date = this.scheduleData.beginTime
					this.defaultBeginTime = Date.parse(new Date(date))
					date = this.scheduleData.endTime
					this.defaultEndTime = Date.parse(new Date(date))
					var label = this.scheduleData.label
					this.items[0] = label
					if (label == "活动日程") {
						this.disable = true
					}
					var frequency = this.scheduleData.frequency
					var times = frequency.substring(1, 2)
					for (var i = 0; i < this.frequencyRange[1].length; i++) {
						if (times == this.frequencyRange[1][i]) {
							this.frequencyIndex[1] = i
						}
					}
					var unit = frequency.substring(2, 3)
					for (var i = 0; i < this.frequencyRange[2].length; i++) {
						if (this.frequencyRange[2][i] == unit) {
							this.frequencyIndex[2] = i
						}
					}
					var remind = this.scheduleData.remind
					console.log(remind)
					for (var i = 0; i < this.remindRange.length; i++) {
						if (this.remindRange[i].text == remind) {
							this.value = this.remindRange[i].value
						}
					}
					this.date = this.scheduleData.repeatEndTime

				},
			});
		},
		computed: {
			startDate() {
				return this.getDateType('start');
			},
			endDate() {
				return this.getDateType('end');
			}
		},
		methods: {
			onClickItem(e) {
				if (this.current != e.currentIndex) {
					this.current = e.currentIndex;
					this.scheduleData.label = this.items[this.current];
				}
			},
			submit(ref) {
				this.$refs[ref].validate().then(res => {
					if (this.scheduleData.beginTime > this.scheduleData.endTime) {
						this.$refs.message.open()
					} else {
						var url = this.apiUrl + 'schedule/update?uid=' + this.uid + '&id=' + this.scheduleData.id
						console.log(url)
						console.log(this.scheduleData)
						uni.request({
							url: this.apiUrl + 'schedule/update?uid=' + this.uid + '&id=' + this
								.scheduleData.id,
							method: 'PUT',
							data: JSON.stringify(this.scheduleData),
							success: (res) => {
								uni.showModal({
									title: '编辑成功',
									success: function(res) {
										if (res.confirm) {
											uni.navigateBack({
												delta: 1
											});
										} else if (res.cancel) {
											uni.navigateBack({
												delta: 1
											});
										}
									}
								})
							},
							fail() {
								uni.showModal({
									title: '编辑失败'
								})
							}
						});
					}
				}).catch(err => {
					console.log('表单错误信息：', err);
				})
			},
			deleteSchedule() {
				console.log("删除日程")
				uni.request({
					url: this.apiUrl + 'schedule/' + this.id,
					method: 'DELETE',
					success: (res) => {
						uni.showToast({
							title: `删除成功`
						})
						uni.navigateBack({
							delta: 1
						});
					},
					fail: (err) => {
						return uni.showToast({
							icon: 'loading',
							title: '请求失败'
						})
						reject(err)
					}
				});
			},
			changeBegin(e) {
				this.scheduleData.beginTime = e;
			},
			changeEnd(e) {
				this.scheduleData.endTime = e;
			},
			remindChange(e) {
				this.value = e
				this.scheduleData.remind = this.remindRange[e].text;
			},
			frequencyChange(e) {
				var column = e.detail.column;
				var value = e.detail.value;
				this.frequencyIndex[column] = value;
				this.scheduleData.frequency = this.frequencyRange[0][this.frequencyIndex[0]] + this.frequencyRange[1][this
					.frequencyIndex[1]
				] + this.frequencyRange[2][this.frequencyIndex[2]];
			},
			bindDateChange: function(e) {
				this.date = e.detail.value
				this.scheduleData.repeatEndTime = e.detail.value
			},
			getDateType(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate() + 1;

				if (type === 'start') {
					year = year - 60;
				} else if (type === 'end') {
					year = year + 2;
				}
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			navToActivity() {
				if (this.scheduleData.label == "活动日程" && this.scheduleData.activityId != 0) {
					uni.navigateTo({

					})
				} else {
					uni.showToast({
						icon: 'none',
						title: `无法跳转`
					})
				}
			}
		}
	};
</script>

<style>
	.updateSchedule-label {
		margin: auto 30rpx;
	}

	.updateSchedule-submit {
		margin: 30rpx;
		margin-bottom: 30px;
	}
</style>
<style lang="scss">
	.updateSchedule-info {
		padding: 1px;
		background-color: #fff;
	}

	.button {
		display: flex;
		align-items: center;
		height: 35px;
		margin-left: 10px;
	}

	.updateSchedule {
		display: flex;
		flex-direction: column;
		justify-content: center;
	}

	.uni-px-5 {
		padding-left: 10px;
		padding-right: 10px;
	}

	.uni-pb-5 {
		padding-bottom: 10px;
	}
</style>
